﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Client.TaskService;
using TaskManagement.ModelLayer;
using System.Text.RegularExpressions;

namespace Client
{
    public partial class TaskManagementForm : Form
    {
        private BindingSource _bs;
        private Regex _numbersOnlyRegex;

        public TaskManagementForm()
        {
            InitializeComponent();
            _numbersOnlyRegex = new Regex(@"(\d|[\b])+");
        }

        # region Task
        private void taskTab_Enter(object sender, EventArgs e)
        {
            using (TaskServiceClient service = new TaskServiceClient("nettcp"))
            {
                Task t = new Task();
                _bs = new BindingSource();
                _bs.DataSource = service.SearchTasks(t);
                _bs.AllowNew = false;
                _bs.CurrentChanged += new EventHandler(_bs_CurrentChanged);
                dataGridViewTask.DataSource = _bs;
                
                if (_bs.Count > 0)
                {
                    t = (Task)_bs[0];
                    UpdateTaskControls(t);
                }
            }
        }

        /// <summary>
        /// Displayes data from the datagridview in the controls above
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _bs_CurrentChanged(object sender, EventArgs e)
        {
            BindingSource bs = (BindingSource)sender;
            Task t =  (Task)bs.Current;
            if(t != null)
            UpdateTaskControls(t);
        }

        private void UpdateTaskControls(Task t)
        {
            textBoxTaskId.Text = t.Id.ToString();
            textBoxTaskAccount.Text = t.Account;
            textBoxTaskTag.Text = t.Tag;
            textBoxTaskDelivery.Text = t.Delivery;
            textBoxTaskDescription.Text = t.Description;
            textBoxAssignedTo.Text = t.AssignedTo;
            dateTimePickerTask.Value = (DateTime)t.Date;
            comboBoxTaskStatus.SelectedItem = t.Status;
            textBoxTaskEstimate.Text = t.Estiamte.ToString();
            textBoxTaskTimeSpent.Text = t.TimeSpent.ToString();
        }

        private void buttonCreateTask_Click(object sender, EventArgs e)
        {

            using (TaskServiceClient service = new TaskServiceClient("nettcp"))
            {
                Task t = CreateTaskFromControls();

                int result = service.CreateTask(t);
                if (result > 0)
                {
                    t.Id = result;
                    _bs.Add(t);
                    _bs.MoveLast();
                    dateTimePickerTask.Checked = true;
                }
                else
                {
                    MessageBox.Show(this,"Could not create task","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                
            }
        }

        private void buttonDeleteTask_Click(object sender, EventArgs e)
        {
            if (dataGridViewTask.SelectedRows.Count == 0)
            {
                MessageBox.Show(this, "Cannot delete while no items are selected", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {

            DialogResult dr = MessageBox.Show(this,"Are you sure you want to delete the seleted task(s)?"
                ,"Delete",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                int result = 0;
                List<Task> tasksToDelete = new List<Task>();
                using (TaskServiceClient service = new TaskServiceClient("nettcp"))
                {
                    foreach (DataGridViewRow row in dataGridViewTask.SelectedRows)
                    {
                        Task t = (Task)row.DataBoundItem;
                        tasksToDelete.Add(t);
                    }

                    result = service.DeleteTasks(tasksToDelete);
                    
                }
                if (result != 0)
                {
                    foreach (Task t in tasksToDelete)
                    {
                        _bs.Remove(t);
                    }

                    if (_bs.Count != 0)
                    {
                        dataGridViewTask.Rows[_bs.Position].Selected = true;
                    }

                }
                else
                {
                    MessageBox.Show(this, "Unable to delete task(s)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            }

        }
        

        private void buttonUpdateTask_Click(object sender, EventArgs e)
        {
            if (dataGridViewTask.SelectedRows.Count > 1)
            {
                MessageBox.Show(this, "Cannot update while more than one item is selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                Task current = (Task)_bs.Current;
                if (current != null)
                {
                    Task task = CreateTaskFromControls();
                    task.Id = current.Id;
                    int result = 0;
                    using (TaskServiceClient service = new TaskServiceClient("nettcp"))
                    {
                        task.Id = current.Id;
                        result = service.UpdateTask(task);
                    }

                    if (result != 0)
                    {
                        current.Account = task.Account;
                        current.Date = task.Date;
                        current.Delivery = task.Delivery;
                        current.Description = task.Description;
                        current.Estiamte = task.Estiamte;
                        current.Status = task.Status;
                        current.Tag = task.Tag;
                        current.TimeSpent = task.TimeSpent;
                        _bs.ResetItem(_bs.Position);
                    }
                    else
                    {
                        MessageBox.Show(this, "Could not update task", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show(this, "Cannot update because no item is selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            
        }

        /// <summary>
        /// Creates a task from the data in the controls
        /// </summary>
        /// <returns>The new task object</returns>
        private Task CreateTaskFromControls()
        {
            Task t = new Task();
            if(!string.IsNullOrEmpty(textBoxTaskId.Text))
                t.Id = int.Parse(textBoxTaskId.Text);

            t.Account = textBoxTaskAccount.Text;
            t.Date = dateTimePickerTask.Value;
            t.Delivery = textBoxTaskDelivery.Text;
            t.Description = textBoxTaskDescription.Text;
            if (comboBoxTaskStatus.SelectedItem != null)
            {
                t.Status = comboBoxTaskStatus.SelectedItem.ToString();
            }
            else
            {
                t.Status = "Pending";
            }

            t.Tag = textBoxTaskTag.Text;

            if (!string.IsNullOrEmpty(textBoxTaskEstimate.Text))
                t.Estiamte = int.Parse(textBoxTaskEstimate.Text);
            else
                t.Estiamte = 0;

            if (!string.IsNullOrEmpty(textBoxTaskTimeSpent.Text))
                t.TimeSpent = int.Parse(textBoxTaskTimeSpent.Text);
            else
                t.TimeSpent = 0;

            return t;
        }

        # endregion

        private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!_numbersOnlyRegex.IsMatch(e.KeyChar.ToString()))
                e.Handled = true;
        }

        private void buttonClearTasksControls_Click(object sender, EventArgs e)
        {
            textBoxTaskId.Clear();
            textBoxTaskAccount.Clear();
            textBoxTaskDelivery.Clear();
            textBoxTaskDescription.Clear();
            textBoxTaskEstimate.Clear();
            textBoxTaskTag.Clear();
            textBoxTaskTimeSpent.Clear();
            textBoxAssignedTo.Clear();
            comboBoxTaskStatus.SelectedItem = null;
            dateTimePickerTask.Value = DateTime.Today;
            dateTimePickerTask.Checked = false;
           
        }

        private void buttonTaskSearch_Click(object sender, EventArgs e)
        {
            Task t = new Task();

            if (!string.IsNullOrEmpty(textBoxTaskAccount.Text))
                t.Account = textBoxTaskAccount.Text;

            if (!string.IsNullOrEmpty(textBoxTaskDelivery.Text))
                t.Delivery = textBoxTaskDelivery.Text;

            if (!string.IsNullOrEmpty(textBoxTaskDescription.Text))
                t.Description = textBoxTaskDescription.Text;

            if (!string.IsNullOrEmpty(textBoxTaskEstimate.Text))
                t.Estiamte = int.Parse(textBoxTaskEstimate.Text);

            if (!string.IsNullOrEmpty(textBoxTaskId.Text))
                t.Id = int.Parse(textBoxTaskId.Text);

            if (!string.IsNullOrEmpty(textBoxTaskTimeSpent.Text))
                t.TimeSpent = int.Parse(textBoxTaskTimeSpent.Text);

            if (!string.IsNullOrEmpty(textBoxTaskTag.Text))
                t.Tag = textBoxTaskTag.Text;

            if (!String.IsNullOrEmpty(comboBoxTaskStatus.SelectedText))
                t.Status = comboBoxTaskStatus.SelectedValue.ToString();

            if (dateTimePickerTask.Checked)
                t.Date = dateTimePickerTask.Value;

            using (TaskServiceClient service = new TaskServiceClient("nettcp"))
            {
                _bs.DataSource = service.SearchTasks(t);
                dataGridViewTask.Focus();
                _bs.MoveFirst();
            }
        }


    }
}
